<template>
  <div v-loading.body="loading.state">
    <el-form :inline="true" ref="data-form" label-width="100px" class="text-left" :model="templatemode">
      <el-form-item label="模板姓名:" v-role="0x070107" prop="input" :rules="[{
            required: true,
            message: '请输入模板编号',
            trigger: 'blur'
          }]">
        <el-input v-model="templatemode.input" placeholder="请输入内容"></el-input>
      </el-form-item>
      <el-form-item label="委托方" prop="prinCode" v-role="0x040207" :rules="[{
            required: true,
            message: '请选择',
            trigger: 'blur'
          }]">
        <el-select v-model="templatemode.prinCode" placeholder="请选择" clearable>
          <el-option v-for="{prinId,prinName} in clientList" :key="prinId" :label="prinName" :value="prinId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="上传文件" v-if="flag">
        <file-upload ref="upload_case_import" @success="uploadSuccess"></file-upload>
      </el-form-item>
    </el-form>
    <el-table style="width: 100%" :data="tableData" height='300'>
      <el-table-column prop="celltemplateName" label="名称" width="200">
      </el-table-column>
      <el-table-column prop="cellType" label="类型" width="200">
      </el-table-column>
      <el-table-column prop="cellLength" label="长度" width="200">
      </el-table-column>
      <el-table-column prop="relateName" label="映射字段" min-width="80">
        <template scope="scope">
          <el-popover trigger="hover" placement="bottom">
            <p class="text-left">字段名称: {{getCelltemplateName(scope)}}</p>
            <p class="text-left">字段CODE: {{getCelltemplateCode(scope)}}</p>
            <p class="text-left">字段类型: {{getCelltemplateType(scope)}}</p>
            <p class="text-left">字段长度: {{getCelltemplateLength(scope)}}</p>
            <div slot="reference" class="name-wrapper">
              <el-select @change="selectVal" v-model="scope.row.relateName" placeholder="请选择" clearable>
                <el-option v-for="item in optionAble" :key="item.id" :label="item.name" :value="item.name">
                </el-option>
              </el-select>
            </div>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>
    <el-button @click="submit">确定</el-button>
    <el-button @click="close">取消</el-button>
  </div>
</template>
<script>
  import servers from '@/config/servers'
  import net from '@/util/net'
  import { mapState } from 'vuex'
  import FileUpload from '@/components/FileUpload'
  export default {
    name: 'case-excel-import',
    data() {
      return {
        loading: {
          state: false
        },
        templatemode: {
          input: '', // 模板名称
          prinCode: ''
        },
        params: [],
        flag: true,
        templateId: '', // 模板ID
        tableData: [],
        rules: {},
        options: [], // 映射字段
        value: [],
        caseDate: {
          disabledDate: (time) => {
            let endTime = this.params.endDate
            if (endTime && (endTime instanceof Date)) {
              return time.getTime() > endTime.getTime()
            }
          }
        },
        endDate: {
          disabledDate: (time) => {
            let startTime = this.params.caseDate
            if (startTime && (startTime instanceof Date)) {
              return time.getTime() < startTime.getTime()
            }
          }
        }
      }
    },
    computed: {
      ...mapState({
        clientList: state => state.caseManage.client_list
      }),
      optionAble() {
        let data = this.tableData.map(v => v.relateName)
        let arr = this.options.filter(v => {
          let obj = data.find(val => {
            return v.name === val
          })
          return !obj
        })
        return arr
      }
    },
    methods: {
      /**
       * 获取映射字段名称
       */
      getCelltemplateName(scope) {
        let item = this.options.find(v => v.name === scope.row.relateName)
        console.log(item)
        if (item) {
          return item.name
        }
      },
      /**
       *  获取映射字段CODE
       */
      getCelltemplateCode(scope) {
        let item = this.options.find(v => v.name === scope.row.relateName)
        console.log(item)
        if (item) {
          return item.code
        }
      },
      /**
       * 获取映射字段类型
       */
      getCelltemplateType(scope) {
        let item = this.options.find(v => v.name === scope.row.relateName)
        console.log(item)
        if (item) {
          return item.type
        }
      },
      /**
       * 获取映射字段长度
       */
      getCelltemplateLength(scope) {
        let item = this.options.find(v => v.name === scope.row.relateName)
        console.log(item)
        if (item) {
          return item.length
        }
      },
      selectVal(ele) {},
      refreshData(modifyData) {
        this.flag = false
        this.tableData = modifyData.excelTemplateList
        this.templatemode.input = modifyData.templateName
        this.templateId = modifyData.id
        this.templatemode.prinCode = modifyData.clientName
        net.send({
          server: servers.ConfigManage.get_relate_list,
          loading: this.loading
        }).then(
          data => {
            this.options = data.content
          },
          ({ reason }) => {
            this.$message(reason)
          }
        )
      },
      uploadSuccess(file) {
        net.send({
          server: servers.ConfigManage.excel_template,
          data: {
            fileId: file.id
          },
          loading: this.loading
        }).then(data => {
          data.map(v => { v.relateName = '' })
          this.tableData = data
          this.$message('Excel导入成功')
          this.$emit('success')
          net.send({
            server: servers.ConfigManage.get_relate_list,
            loading: this.loading
          }).then(
            data => {
              this.options = data.content
            },
            ({ reason }) => {
              this.$message(reason)
            }
          )
        }, (err) => {
          if (!err.object) {
            this.$message({
              type: 'info',
              message: 'Excel导入失败！Excel数据格式错误'
            })
            return
          }
          this.$emit('errMsg', err.object)
        })
      },

      /**
       * 委案日期change事件
       */
      caseDataChange() {
        if (this.params.caseDate && (this.params.caseDate instanceof Date)) {
          let caseDate = new Date(this.params.caseDate.getTime())
          this.params.endDate = new Date(caseDate.setMonth(caseDate.getMonth() + 3))
        }
      },
      /**
       * 确定
       */
      submit() {
        this.$refs['data-form'].validate((valid) => {
          if (!valid) {
            return
          }
          if (this.flag) {
            // 获取上传文件
            let file = this.$refs['upload_case_import'].getFile()
            // 查看是否上传完成
            if (!file) {
              this.$message('请上传导入文件')
              return
            }
          }
          // 发送导入请求
          net.send({
            server: servers.ConfigManage.add_excel_template,
            data: { excelTemplateList: this.tableData, templateName: this.templatemode.input, id: this.templateId, clientName: this.templatemode.prinCode },
            loading: this.loading
          }).then(data => {
            this.$message('导入成功')
            this.$emit('success')
            this.close()
          }, (err) => {
            if (!err.object) {
              this.$message({
                type: 'info',
                message: '导入失败！Excel数据格式错误'
              })
              return
            }
            this.$emit('errMsg', err.object)
          })
        })
      },
      /**
       * 取消
       */
      close() {
        if (this.flag) {
          this.$refs['upload_case_import'].reset()
        }
        this.tableData = []
        this.templatemode.input = ''
        this.templatemode.prinCode = ''
        this.$emit('close')
        this.$refs['data-form'].resetFields()
        // this.$refs['databox'].refresh()
      }
    },
    components: {
      FileUpload
    }
  }

</script>
<style scoped>
  .el-table .info-row {
    background: #c9e5f5;
  }

  .el-table .positive-row {
    background: #e2f0e4;
  }

</style>
